"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const R = require("request");
let resources = [
    {
        name: '听儿歌',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '1',
    },
    {
        name: '讲故事',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '2',
    },
    {
        name: '学英语',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '3',
    },
    {
        name: '读古诗',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '4',
    },
    {
        name: '三字经',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '5',
    },
    {
        name: '伴眠曲',
        url: 'http://www.alilo.com.cn/gw/resource/recommendMusic',
        classify: '6',
    }
];
let jsonArr = [];
/**
 * 获取json格式恩数据
 * @param {Object} r
 * @return {Promise<Object>}
 */
function getJsondata(r) {
    return new Promise((resolve, reject) => {
        let params = {
            url: r.url,
            form: {
                classify: r.classify
            }
        };
        R.post(params, function (error, res, data) {
            if (error) {
                reject(error);
            }
            else {
                if (data) {
                    data = JSON.parse(data);
                    // console.log(data);
                    resolve(data.content.recommendMusicList);
                }
            }
        });
    });
}
/**
 * 下载数据
 * @param {Object} obj
 * @return {Promise<any>}
 */
function downloadData(obj) {
    return new Promise((resolve, reject) => {
        let name = obj.name;
        let path = obj.path;
        let dir = './public/' + resources[obj.classify - 1]['name'];
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
        console.log("开始下载 <<" + name + ">> \r\n");
        R.get(path)
            .pipe(fs.createWriteStream(dir + '/' + name + '.mp3').on('finish', () => { console.log(name + '下载完成'); })
            .on('close', () => resolve("下载完成")));
    });
}
async function run() {
    // 下载json格式的数据
    for (let r of resources) {
        let data = await getJsondata(r);
        jsonArr.push(data);
    }
    // 下载视频
    for (let arr of jsonArr) {
        for (let obj of arr) {
            let log = await downloadData(obj);
        }
    }
}
run();
